<template>
  <div class="channel-edit">
    <!-- 我的频道 -->
    <van-cell :border="false">
      <div slot="title"
        class="title-text">我的频道</div>

      <van-button slot="default"
        class="edit-btn"
        size="mini"
        round
        type="danger"
        plain
        @click="isEdit = !isEdit">{{isEdit? '已完成':'编辑'}}</van-button>
    </van-cell>
    <!-- 内容 -->
    <van-grid class="my-grid"
      :border="false"
      :gutter="10">
      <van-grid-item class="grid-item"
        v-for="(channel,index) in myChannels"
        :key="channel.id"
        @click="onMyChannels(channel,index)">

        <!-- 删除图标按钮 -->
        <van-icon v-show="isEdit && !fiexdChannel.includes(channel.id)"
          name="clear"
          slot="icon">

        </van-icon>
        <!-- 清除文字 -->
        <span slot="text"
          class="text"
          :class="{active:index===active }">{{channel.name}}</span>
      </van-grid-item>
    </van-grid>
    <!-- 频道推荐 -->
    <van-cell :border="false">
      <div slot="title"
        class="title-text">推荐频道</div>

    </van-cell>
    <!-- 内容 -->
    <van-grid class="recommend-grid"
      :border="false"
      :gutter="10">
      <van-grid-item class="grid-item"
        v-for="(item,index) in recommendChannels"
        :key="index"
        :text="item.name"
        icon="plus"
        @click="addChannels(item)" />
    </van-grid>
  </div>
</template>

<script>

// 导入全部频道列表请求
import { getChannelsList, addUserChannels, deleteUserChannels } from '@/api/channel.js'
import { mapState } from 'vuex'
import { setItem } from '@/utils/index.js'

export default {
  name: 'ChannelEdit',
  props: {
    // 传递频道列表
    myChannels: {
      type: Array,
      require: true
    },
    // 控制首页选中文字高亮效果
    active: {
      type: Number,
      require: true
    }

  },
  data () {
    return {
      // 所有频道
      allChannel: [],
      // 控制编辑按钮状态
      isEdit: false,
      // 固定频道bu允许删除
      fiexdChannel: [0]
    }
  },
  created () {
    this.loadChannelsList()
  },
  // 计算属性会观测内部依赖数据的变化
  // 如果依赖的数据发生变化，则计算属性会重新执行
  computed: {
    ...mapState(['user']),
    // eslint-disable-next-line vue/return-in-computed-property
    recommendChannels () {
      return this.allChannel.filter(channel => {
        // 数组的 filter 方法：遍历数组，把符合条件的元素存储到新数组中并返回
        return !this.myChannels.find(myChannels => {
          return myChannels.id === channel.id
        })
      })
    }

    // recommendChannels () {
    //   const channels = []
    //   this.allChannels.forEach(channel => {
    //     // find 遍历数组，找到满足条件的元素项
    //     const ret = this.myChannels.find(myChannel => {
    //       return myChannel.id === channel.id
    //     })

    //     // 如果我的频道中不包括该频道项，则收集到推荐频道中
    //     if (!ret) {
    //       channels.push(channel)
    //     }
    //   })

    //   // 把计算结果返回
    //   return channels
    // }
  },
  methods: {
    // 获取频道列表
    async loadChannelsList () {
      try {
        const { data: res } = await getChannelsList()
        console.log(res)
        this.allChannel = res.data.channels
      } catch (err) {
        this.$toast('获取数据失败')
      }
    },
    // 添加频道
    async addChannels (channel) {
      this.myChannels.push(channel)
      // 数据持久化
      if (this.user) {
        try {
          // 已登录，把数据请求接口放到线上
          await addUserChannels([{
            id: channel.id, // 频道id
            seq: this.myChannels.length // 序号
          }])
        } catch (err) {
          this.$toast('保存失败，请稍后重试')
        }
      } else {
        // 未登录，把数据存储到本地存储
        setItem('channels', this.myChannels)
      }
    },

    // 点击切换频道到主页
    onMyChannels (channels, index) {
      if (this.isEdit) {
        // 编辑状态
        // 如果是固定频道则不删除
        if (this.fiexdChannel.includes(channels.id)) {
          return
        }
        // 删除频道
        this.myChannels.splice(index, 1)
        // 如果删除频道之前的频道
        if (index <= this.active) {
          this.$emit('updata-active', this.active - 1, true)
        }
        //  // 4. 处理持久化
        this.deleteChannel(channels)
      } else {
        // 为编辑状态
        this.$emit('updata-active', index, false)
      }
    },

    // 删除频道的处理逻辑
    async deleteChannel (channel) {
      try {
        if (this.user) {
          // 已登录，将数据更新到线上
          await deleteUserChannels(channel.id)
        } else {
          // 未登录，将数据保存到本地存储

          setItem('channels', this.myChannels)
        }
      } catch (err) {
        this.$toast('删除频道失败，请稍后重试')
      }
    }

  }

}
</script>

<style lang="less" scoped>
.channel-edit{
 padding: 85px 0;
 .title-text{
   font-size: 32px;
   color: #333333;
 }
//  编辑按钮
 .edit-btn{
    width: 104px;
    height: 48px;
    font-size: 24px;
    color: #f85959;
    border: 1px solid #f85959;
 }

  /deep/ .van-grid-item__content {
      background-color: #f5f5f6;
      .van-grid-item__text {
        color: #222;
        font-size: 28px;
      }
  }

  //频道推荐
   /deep/ .grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text, .text {
        font-size: 28px;
        color: #222;
        margin-top: 0;
      }
      .active {
        color: red;
      }
      .van-grid-item__icon-wrapper {
        position: unset;
      }
    }
  }

  /deep/ .my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        right: 10px;
        top: -10px;
        font-size: 30px;
        color: #cacaca;
        z-index: 99;
      }
    }
  }

  /deep/ .recommend-grid {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 28px;
          margin-right: 6px;
        }
      }
    }
  }
}

</style>
